import { Injectable } from '@nestjs/common';
import { AccessTokenEntity } from '../entities';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class LoginService {
  constructor(@InjectRepository(AccessTokenEntity) private readonly accessTokenRepository: Repository<AccessTokenEntity>,) { }
  async login(token: string) {
    try {
      const expired = new Date().getTime() + 60 * 1000
      await this.accessTokenRepository.save({ value: token, expired_at: new Date(expired) })
    } catch (error) {
      console.log(error)
    }
  }
  async getAccessToken(token: string) {
    const accessToken = await this.accessTokenRepository.findOneBy({ value: token })
    return accessToken
  }
  async checkToken(token: string) {
    const accessToken = await this.getAccessToken(token)
    if (!accessToken) {
      return false
    }
    if (new Date(accessToken.expired_at).getTime() > new Date().getTime()) {
      return true
    } else {
      return false
    }

  }
}
// 用户登录 验证用户名密码 返回token token存入数据库 同时生成一个过期时间远大于token的refreshtoekn
// 其中用户和token的关系是一对多的关系 token和refreshtoken是一对一的关系

// 挟带token访问需要验证的api
